<template>
  <div>
    <page-header-wrapper></page-header-wrapper>
    <a-card style="margin-top: 20px">
      <div class="table-page-search-wrapper">
        <a-form :form="searchForm" layout="inline">
          <a-row :gutter="48">
            <SearchFormItems
              :searchKeys="ProductListSearchKeys"
              :getDataWithKey="getDataWithKey"
            >
            </SearchFormItems>
            <a-col :md="6" :sm="6" class="advanced_butns">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="search">搜索</a-button>
                <a-button @click="reset">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <div class="cont_box">
      <div class="table_header flex-between">
        <div class="table_name">{{ pageTitle }}</div>
        <div class="table_butns flex-end">
          <a-button type="primary" @click="handleClick('accept', null)"
            >全部接单</a-button
          >
          <a-button type="primary" @click="handleClick('add', null)"
            >无图模式</a-button
          >
          <a-button type="primary" @click="handleClick('add', null)"
            >全部拒单</a-button
          >
          <a-button @click="handleClick('add', null)">批量缺图</a-button>
          <a-button @click="handleClick('add', null)">批量下图</a-button>
        </div>
      </div>
      <a-table
        :columns="ProductListColumn"
        :dataSource="dataSource"
        :pagination="pagination"
        :rowKey="(it) => it.id"
        :loading="loading"
        :rowSelection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
        }"
        :expandedRowKeys="curExpandedRowKeys"
        @expand="getInnerData"
        binvested
      >
        <div class="flex-center" r slot="onAddress" slot-scope="text, record">
          <span>物流单号: {{ record.deliverySn }}</span>
        </div>
        <div slot="expandedRowRender" slot-scope="record">
          <a-spin :spinning="importLoading">
            <a-table
              :columns="PurchaseExpandColumn"
              :dataSource="innerData"
              :pagination="false"
              :rowKey="(it) => it.id"
              :loading="innerLoading"
            >
              <div slot="onGoods" slot-scope="text, record">
                <img :src="record.effectImgUrl" />
              </div>
            </a-table>
          </a-spin>
        </div>
      </a-table>
      <pagination
        :total="total"
        :page.sync="page"
        :size.sync="size"
        :onPageSizeChange="onPageSizeChange"
        :onShowSizeChange="onShowSizeChange"
      />
      <a-modal
        :title="modalType == 'edit' ? '编辑库位' : '新建库位'"
        v-model="editVisible"
        destroyOnClose
        @ok="sureModal"
        width="600px"
      >
        <div class="modal_body_cont">
          <a-form
            :form="modalForm"
            :label-col="{ span: 7 }"
            :wrapper-col="{ span: 15 }"
          >
            <modalFormItem
              :searchKeys="ProductListModalKeys"
              :getDataWithKey="getDataWithKey"
            ></modalFormItem>
          </a-form>
        </div>
      </a-modal>
    </div>
  </div>
</template>

<script>
import {
  ProductListSearchKeys,
  ProductListColumn,
  ProductListModalKeys,
  PurchaseExpandColumn,
} from "./config";
import {
  productList,
  productUpdate,
  productDelete,
  spuImport,
} from "@/api/product";

import { applyStore, getOrderList, orderDetail} from "@/api/wms-store";

export default {
  name: "storage-loacation-list",
  data() {
    return {
      pageTitle: "",
      ProductListSearchKeys,
      PurchaseExpandColumn,
      ProductListColumn,
      ProductListModalKeys,
      dataSource: [],
      pagination: false,
      page: 1,
      size: 50,
      innerData:[],
      total: 0,
      loading: false,
      curExpandedRowKeys: [],
      selectedRowKeys: [],
      searchForm: this.$form.createForm(this, { name: "product_list_search" }),
      modalForm: this.$form.createForm(this, { name: "product_list_modal" }),
      editVisible: false,
      batchUploading: false,
      batchDownloading: false,
      exportLoading: false,
      importLoading: false,
      fileList: [],
      modalType: "add",
      sortString: "createTime,desc",
    };
  },
  computed: {
    getDataWithKey() {
      return (key) => {
        //  // 订单状态（0：待接单；1：已拒单；2：已接单；10：部份入库；20：待发货 21：已发货）
        switch (key) {
          case "status":
            return [
              { key: "0", value: "待接单" },
              { key: "1", value: "已拒单" },
              { key: "2", value: "已接单" },
              { key: "10", value: "部份入库" },
              { key: "20", value: "待发" },
              { key: "21", value: "已发货" },
            ];
          default:
            return [];
        }
      };
    },
  },
  async created() {
    this.pageTitle = this.$route?.meta?.title;
    this.getList();
  },
  methods: {
    search() {
      this.page = 1;
      this.getList();
    },
    reset() {
      this.searchForm.resetFields();
      this.page = 1;
      this.getList();
    },
    onPageSizeChange(page, size) {
      this.selectedRowKeys = [];
      this.page = page;
      this.getList(page, size);
    },
    onShowSizeChange(page, size) {
      this.selectedRowKeys = [];
      this.page = page;
      this.size = size;
      this.getList(page, size);
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    importSpu(data) {
      this.importLoading = true;
      const formData = new FormData();
      formData.append("file", data.file);
      spuImport(formData).then((res) => {
        if (res?.code == 200) {
          this.$message.success("导入成功");
          this.getList();
        } else {
          this.$message.error(res?.message);
        }
        this.importLoading = false;
      });
    },
    batchOpres(type) {},
    exportExcel() {},
    onOffLine({ id }) {
      productUpdate(id).then((res) => {
        console.log("hahahah", res);
        this.getList();
      });
    },
    cameltoLine(value) {
      return value.replace(/([A-Z])/g, "_$1").toLowerCase();
    },
    // 获取列表
    async getList(currentPage, currentSize) {
      this.loading = true;
      const { page, size, sortString } = this;

      let sort = sortString.split(",");
      this.searchForm.validateFields(async (err, values) => {
        if (!err) {
          let params = {
            pageNum: currentPage || page,
            pageSize: currentSize || size,
            ...values,
            expireDate:
              (values?.expireDate && values?.expireDate.format("YYYY-MM-DD")) ||
              "",
            orders: [
              {
                column: this.cameltoLine(sort[0]),
                asc: sort[1] == "desc" ? false : true,
              },
            ],
          };
          // getStoreList
          const res = await productList(params);
          if (res?.success) {
            this.total = res?.data?.total || 0;
            this.dataSource = res?.data?.list || [];
          } else {
            this.$message.error(res?.message);
          }
          this.loading = false;
        } else {
          this.loading = false;
        }
      });
    },
    deleteProd(record) {
      this.$confirm({
        title: `确定要删除吗？`,
        content: "",
        okText: `删除`,
        okType: "danger",
        cancelText: "取消",
        onOk: () => {
          productDelete(record.id).then((res) => {
            this.$message.success("操作成功");
            this.getList();
          });
        },
      });
    },
    handleClick(type) {
      if (type == "accept") {
      } else if (type == "reject") {
      } else if (type == "") {
      } else if (type == "") {
      } else {
      }
    },
    goDetail(type, record) {
      let params = {
        type,
      };
      if (record) {
        params.id = record?.id;
      }
      this.editVisible = true;
    },
    sureModal() {
      let { companyId } = this;
      this.modalForm.validateFields(async (err, values) => {
        if (!err) {
          applyStore(params).then((res) => {
            if (res?.success) {
              this.$message.success(
                `${modalType == "add" ? "添加" : "编辑"}成功`
              );
              this.editVisible = false;
              this.getList();
            } else {
              this.$message.error(res?.message);
            }
          });
        }
      });
    },
    async getInnerData(expanded, { id = "" }) {
      this.currPurchaseId = id;
      if (this.curExpandedRowKeys.length > 0) {
        let index = this.curExpandedRowKeys.indexOf(id);
        if (index > -1) {
          this.curExpandedRowKeys.splice(index, 1);
        } else {
          this.curExpandedRowKeys.splice(0, this.curExpandedRowKeys.length);
          this.curExpandedRowKeys.push(id);
        }
      } else {
        this.curExpandedRowKeys.push(id);
      }
      if (expanded) {
        await this.getTemplateData(id);
      }
    },
    async getTemplateData(id) {
      this.innerLoading = true;
     
      let purchaseCode;
      this.dataSource.forEach((val) => {
        if (id == val.id) purchaseCode = val.purchaseCode;
      });
      let innerRes = await orderDetail({ purchaseCode: purchaseCode });
      this.innerData = innerRes?.data;
      this.innerLoading = false;
    },
  },
};
</script>
<style scoped>
:deep(.ant-calendar-picker) {
  width: 100% !important;
}
</style>
